package org.robert.export_client.excel.impl;

import com.robert.common.commonutil.util.DateUtils;
import com.robert.common.commonutil.util.LocalDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.robert.export_client.excel.entity.ExcelConstant;
import org.robert.export_client.excel.metadata.DependEntity;
import org.robert.export_client.excel.metadata.ExcelDictEntity;
import org.robert.export_client.excel.metadata.ExcelHeadEntity;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * FieldUtil:
 *
 * @author zhaoshengtao
 * @date 2024/02/28
 */
@Slf4j
public class FieldUtil {


    public static Field getFieldByName(Class<?> clazz, String fieldName) {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            log.warn(e.getMessage(), e);
            return null;
        }
    }

    public static String setFiledByName(String fieldName, Class<?> clazz, Object t, ExcelHeadEntity headEntity) throws IllegalAccessException {
        Optional<Field> field = Optional.ofNullable(getFieldByName(clazz, fieldName));
        if (field.isPresent()) {
            field.get().setAccessible(true);
            Object value = field.get().get(t);
            if (value == null || StringUtils.isBlank(value.toString())) {
                return "";
            }
            // 判断是否需要解析字典
            ExcelDictEntity dictEntity = headEntity.getDictEntity();
            if (dictEntity != null) {
                return setDictValue(dictEntity, (String) value);
            }
            // 是否需要解析时间
            String dateFormat = headEntity.getDateFormat();
            if (value instanceof Date) {
                value =  DateUtils.getDate((Date) value, dateFormat);
            }
            if (value instanceof LocalDateTime) {
                value =  LocalDateUtil.getFormatDate((LocalDateTime) value, dateFormat);
            }
            // 是否需要数据依赖
            if(headEntity.isDepend()){
                DependEntity dependEntity = headEntity.getDependEntity();
                // 获取依赖字段
                String dependField = dependEntity.getDependField();
                Object fieldValue =  value;
                if(StringUtils.isNotBlank(dependField)){
                    // 获取这个字段值
                    Optional<Field> deField = Optional.ofNullable(getFieldByName(clazz, dependField));
                    if(deField.isPresent()){
                        fieldValue = deField.get().get(t);
                    }
                }
                boolean b = ExcelDependService.checkDependValue(dependEntity, fieldValue.toString());
                if (b){
                    if(dependEntity.isFixed()){
                        return dependEntity.getFixedValue();
                    }
                    return String.valueOf(value);
                }
                return ExcelConstant.EMPTY;
            }

            return String.valueOf(value);
        }
        return ExcelConstant.NULL_VALUE; // 或者处理找不到属性的情况
    }

    public static String setFiledByNames(Class<?> clazz,Object t,ExcelHeadEntity headEntity) throws IllegalAccessException {
        String[] fieldNames = headEntity.getFieldNames();
        if(fieldNames == null || fieldNames.length < 1){
            return "";
        }
        StringBuilder valueAll = new StringBuilder();
        String connectType = headEntity.getConnectType();
        int i = 0;
        for (String fieldName : fieldNames) {
            Optional<Field> field = Optional.ofNullable(getFieldByName(clazz, fieldName));
            if (field.isPresent()) {
                field.get().setAccessible(true);
                Object value = field.get().get(t);
                if (value == null || StringUtils.isBlank(value.toString())) {
                    i++;
                    continue;
                }
                // TODO 这里可以有依赖值判断

                String dateFormat = headEntity.getDateFormat();
                if (!StringUtils.isEmpty(dateFormat)) {
                    if (value instanceof LocalDateTime) {
                        value =  LocalDateUtil.getFormatDate((LocalDateTime) value, dateFormat);
                    }
                    if (value instanceof Date) {
                        value = DateUtils.getDate((Date) value, dateFormat);
                    }
                }
                // 最后一个不需要拼接符
                if( i == fieldNames.length - 1){
                    valueAll.append(value);
                }else{
                    valueAll.append(value).append(connectType);
                }
                i++;
            }
        }
        return valueAll.toString();
    }

    public static String setDictValue(ExcelDictEntity dictEntity, String attributeValue ){
        Map<String, String> map = dictEntity.getDictMap();
        // 是否需要分割
        if(dictEntity.isSplit()){
            String connect = dictEntity.getConnect();
            String spilt = dictEntity.getSpilt();
            if(StringUtils.isNotBlank(attributeValue)){
                String[] strings = attributeValue.split(spilt);
                StringBuilder builder = new StringBuilder();
                for (String string : strings) {
                    String s = map.get(string);
                    if(StringUtils.isNotBlank(s)){
                        builder.append(s).append(StringUtils.defaultIfBlank(connect, spilt));
                    }
                }
                return builder.toString();
            }
        }else{
            return map.get(attributeValue);
        }
        return ExcelConstant.NULL_VALUE;
    }

}
